//
//  AYOauthViewController.swift
//  iOSSinaWeb
//
//  Created by yws on 16/5/14.
//  Copyright © 2016年 yws. All rights reserved.
//

import UIKit
import SVProgressHUD


class AYOauthViewController: UIViewController {

    override func loadView() {
        super.loadView()
        view = webView
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = GlobalBKGColor
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(autoFill))
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(close))
        
        navigationItem.title = "登陆"
        
        //https://api.weibo.com/oauth2/authorize?client_id=4279142674&redirect_uri=http://www.baidu.com/
        let urlString = oauthURLString + "?client_id=" + client_id + "&redirect_uri=" + redirect_uri
        
        let url = NSURL(string: urlString)
        AMPrint(items: "\(url)")
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
        
        
        SVProgressHUD.showWithStatus("正在加载")
    }
    
    // MARK: - Action
    
    @objc private func autoFill () {
        //调用js代码
        let jsString = "document.getElementById('userId').value='kbelieveme@vip.qq.com';document.getElementById('passwd').value='y445060477';"
        
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    @objc private func close () {
        
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    // MARK: - lazy
    
     /// webView的懒加载
    private lazy var webView: UIWebView = UIWebView()
    
    
    
}


extension AYOauthViewController: UIWebViewDelegate {
    
    
    //webView加载完成以后调用
    func webViewDidFinishLoad(webView: UIWebView) {
        
        SVProgressHUD.dismiss()
    }
    
    //
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let url = request.URL!
//        AMPrint(items: "request: \(url.absoluteString)")
        if !url.absoluteString.hasPrefix(redirect_uri) {
            AMPrint(items: "request: \(url.absoluteString)")
            return true
        } else {
            let query = url.query!
            let codeString = "code="
            
            if query.hasPrefix(codeString) {
                let code = (query as NSString).substringFromIndex(codeString.characters.count)
                AMPrint(items: "\(code)")
//                let urlString = "oauth2/access_token"
//                
//                let parameters = [
//                    "client_id" : client_id,
//                    "client_secret" : client_secret,
//                    "grant_type" : "authorization_code",
//                    "code" : code,
//                    "redirect_uri": redirect_uri
//                ]
//                
//                AYAFNetworkTool.sharedInstance.request(requestMethod.POST, URLString: urlString, parameters: parameters, success: { (task, responseObject) -> Void in
//                    AMPrint(items: "获取AccessToken成功: \(responseObject)")
//                    
//                    //字典转模型
//                    
//                    if let result = responseObject as? [String : AnyObject] {
//                        let userAcount = AYUserAccount(dict: result)
//                        
//                        AMPrint(items: "\(userAcount)")
//                        
//                        //归档路径
//                        let userAcountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! + "/account.plist"
//                        AMPrint(items: "\(userAcountPath)")
//                        //归档将模型保存到沙盒里面去
//                        NSKeyedArchiver.archiveRootObject(userAcount, toFile: userAcountPath)
//                        
//                    } else {
//                        AMPrint(items: "转失败了")
//                    }
//                    }, failure: { (task, error) -> Void in
//                        AMPrint(items: "失败了: \(error)")
//                })
                
                AYUserAccountViewModel.sharedInstance.loadAccessToken(code, callback: { (error) in
                    if error != nil {
                        AMPrint(items: "\(error)")
                        SVProgressHUD.showWithStatus("您的网络不给力")
                        
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                            self.close()
                        })
                    } else {
                        self.close()
                        
                        let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
                        appDelegate.switchRootViewController(AYWelcomeViewController())
                    }
                    
                })
                
            } else {
                close()
            }
        }
        
        
        return false
    }
}

